import { defineStore } from 'pinia';
import { http } from '@/utils/request';
import type { Profile } from '@/types/index';
import { message } from '@/components/XtxUI';
import router from '@/router';
import useStore from '..';

const useMemberStore = defineStore('member', {
  persist: true,
  state: () => {
    return {
      profile: {} as Profile,
    };
  },
  getters: {
    token(state) {
      return state.profile.token;
    },
    isLogin(state) {
      return state.profile.token ? true : false;
    },
  },
  actions: {
    async login(data: { account: string; password: string }) {
      console.log(111);
      try {
        const res = await http<Profile>('POST', '/login', data);
        console.log('/login', res.data.result);
        this.profile = res.data.result;
        message({
          type: 'success',
          text: '登录成功！',
        });
        const cart = useStore().cart;
        cart.mergeCart();
        // 利用路由器的当前路由的属性。
        router.push((router.currentRoute.value.query.target as string) || '/');
      } catch (e) {
        message({
          type: 'error',
          text: '登录失败',
        });
      }
    },
    // 退出登录
    logout() {
      this.profile = {} as Profile;
      const cart = useStore().cart;
      cart.clearCart(); //退出登录，清空购物车的数据。
      message({
        type: 'success',
        text: '退出登录成功',
      });
    },
    // 发送验证码
    async getCodeBind(mobile: string) {
      const res = await http('get', '/login/social/code', { mobile });
      console.log(res, 'res');
    },

    //已注册，未绑定
    async handlerBindPhone(data) {
      try {
        const res = await http<Profile>('post', '/login/social/bind', data);
        // console.log(res, '@@@');
        this.handlerSuccess(res.data.result);
      } catch (e) {
        message({
          type: 'error',
          text: '登录失败',
        });
      }
    },
    handlerSuccess(profile: Profile) {
      message({
        type: 'success',
        text: '登录成功！',
      });
      this.profile = profile;
      const cart = useStore().cart;
      cart.mergeCart();
      // 第三方登录回调页面
      const { target } = router.currentRoute.value.query;
      // console.log('route', route);
      router.push((target as string) || '/');
    },

    // 已绑定，直接登录
    async loginQQUnionId(data: { unionId: string; source: number }) {
      const res = await http<Profile>('post', '/login/social', data);
      this.handlerSuccess(res.data.result);
    },
    // 未注册,注册登录
    async registerLogin(
      data: {
        account: string;
        mobile: string;
        code: string;
        password: string;
      },
      unionId: string
    ) {
      const res = await http<Profile>(
        'post',
        `/login/social/${unionId}/complement`,
        data
      );
      // 成功处理登录成功函数
      this.handlerSuccess(res.data.result);
    },
  },
});
export default useMemberStore;
